/**
 * 火车票封装的方法
 * @author hongwei 2018-08-03
 */
// +----------------------------------------------------------------------
// | 基本知识
// | isApply=0      0关闭，1开启
// | orderType=0    0因私，1因公
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 目录
// | step01:初始化方法                        _init
// | step02:获取火车票列表                    getTrainList
// | step03:火车票详细信息                    trainInfo
// +----------------------------------------------------------------------
(function(window) {
    'use strict';
    var trainResult = function(params) {
        this.extend(this.params, params);
        this._init();
    };
    trainResult.prototype = {
        //参数
        params: {
            // start_date      : '2018-08-10',
            start_station: '',
            end_station: '',
            numDays: '', //天数
            moveNum: '',
            plane_index: '',
            dayNum : ''
        },
        //step01:初始化操作
        _init: function() {
            var self = this;
            if (typeof(api) == 'undefined') {
                console.log('该插件只能在apicloud下运行');
            } else {
              api.addEventListener({
                  name: 'train_index'
              }, function(ret, err) {
                  index = ret.value.index;
                  self.params.index = index;
                  self.getTrainList(self.params);
              });
                self.dayNum = 1;
                //todo日期平滑效果
                self.calculateTime();
                self.getNumDay(self.params.start_date);
                var confirmTime = getBeforeDate(self.numDays, self.params.start_date);
                self.calculate(confirmTime);
                // self.getTrainList(self.params); //step02:获取火车票列表
                self.train_info(self.params); //step03:火车票详细信息
                self.dateClick();
                self.prefixInteger();
                // self.bindEv();
                // self.bindDate();
                self.timeClick();
            }
        },
        //step02:获取火车票列表
        //三个参数:train_start_time,from_station_name,to_station_name
        getTrainList: function(params) {
          console.log(JSON.stringify(params));
            var self = this;
            console.log(self.dayNum);
            if (parseInt(self.dayNum)+1 <= 30) {
              $('#tran_list').html('');
              var param = {};
              var train_type = '';
              self.plane_index = params.index;
              if (self.plane_index == 2) {
                  train_type = 'G';
              }
              if (self.plane_index == 3) {
                  train_type = 'D';
              }

              self.start_station = params.start_station;
              self.end_station = params.end_station;

              param.url = Config.api.Tickets_Available;
              param.data = {
                  train_start_time: params.start_date,
                  from_station_name: params.start_station,
                  to_station_name: params.end_station,
                  type: train_type
              };
              ajax(param, function(ret) {
                  if (ret.code == 1 && ret.data.length != 0) {
                      var res = ret.data;
                      var html = '';
                      var price = '';
                      var ticket_num = '';
                      $(res).each(function(index, val) {
                          if (val.price == 0) {
                              price = '<p class="price">无票</p>';
                          } else {
                              price = '<p class="price">￥<em class="seat_price">' + val.price + '</em>起</p>';
                          }
                          ticket_num = '<div class="seatNum">';
                          if (Object.keys(val.seat_list).length === 4) {
                              for (var k in val.seat_list) {
                                  if (val.seat_list[k] < 100) {
                                      ticket_num += '<p style="width: 25%;font-size: 0.6rem;">' + k + '(<span style="color:red;">' + val.seat_list[k] + '</span>)张</p>';
                                  } else {
                                      ticket_num += '<p style="width: 25%;font-size: 0.6rem;">' + k + '(<span style="color:#57B158;">' + val.seat_list[k] + '</span>)张</p>';
                                  }
                              }
                          } else {
                              for (var k in val.seat_list) {
                                  if (val.seat_list[k] < 100) {
                                      ticket_num += '<p style="width: 25%;font-size: 0.6rem;">' + k + '(<span style="color:red;">' + val.seat_list[k] + '</span>)张</p>';
                                  } else {
                                      ticket_num += '<p style="width: 25%;font-size: 0.6rem;">' + k + '(<span style="color:#57B158;">' + val.seat_list[k] + '</span>)张</p>';
                                  }
                              }
                          }
                          ticket_num += '</div>';
                          html += '<li>' +
                              '<ul style="overflow:hidden;" class="train_info" data="' + val.train_code + '">' +
                              '<li style="width: 25%; text-align:center;" class="start">' +
                              '<div class="start_message">' +
                              '<p>' + val.start_time + '</p>' +
                              '<p><div class="pass">始</div><span class="start_addr" style="font-size:0.7rem;text-align:center;">' + val.from_station_name + '</span></p>' +
                              '</div>' +
                              '</li>' +
                              '<li style="width: 25%;" class="expend_time">' +
                              '<p class="train_number" style="color:black;font-size:0.8rem;">' + val.train_code + '</p>' +
                              '<i class="iconfont icon-lianjie"></i>' +
                              '<p style="margin-top:-2.5rem;font-size:0.5rem;">' + val.run_time + '</p>' +
                              '</li>' +
                              '<li class="end" style="float:left;width: 25%;text-align:center;">' +
                              '<div class="end_message">' +
                              '<p>' + val.arrive_time + '</p>' +
                              '<p><div class="last">终</div><span class="end_addr" style="font-size:0.7rem;text-align:center;">' + val.to_station_name + '</span></p>' +
                              '</div>' +
                              '</li>' +
                              '<li class="end" style="float:right;width: 25%;">' +
                              '<div class="seat_message">' +
                              price +
                              '</div>' +
                              '</li>' +
                              ticket_num +
                              '</ul>' +
                              '</li>';
                      });
                      $('#tran_list').html(html);
                  } else {
                    $('#tran_list').html('');
                    $toast(ret.msg);
                  }
              })
            } else {
              $('#tran_list').html('');
              $alert('火车购票只限于一个月之内，请重新选择日期');
            }
        },
        //step03:火车票详细信息
        //四个参数
        train_info: function(params) {
            var self = this;
            $("#tran_list").on("click", '.train_info', function(ret) {
                //console.log(JSON.stringify(ret));
                var param = {
                    train_code: $(this).attr('data'), //车次
                    start_date: params.start_date, //开始日期
                    start_station: params.start_station, //起始站
                    end_station: params.end_station, //终点站
                };
                params = $.extend(params, param);
                openWin('train_message', './train_message_win.html', params);
            });
        },
        //计算天数，日期位移
        getNumDay: function(aircraf_start_time) {
            var self = this;
            var date = new Date();
            var nowDate = date.getFullYear() + '-' + self.prefixInteger((date.getMonth() + 1), 2) + '-' + self.prefixInteger(date.getDate(), 2); //获取当前日期
            if (aircraf_start_time.split('/').join("-") == nowDate) {
                self.numDays = 0;
            } else {
                self.numDays = parseInt(Math.abs((new Date(aircraf_start_time)).getTime() - date.getTime()) / 3600 / 24 / 1000) + 1; //选择的日期(毫秒)
                self.dayNum = self.numDays;
            }
            if (self.numDays <= 5) {
                self.numDays = self.numDays;
                if (self.numDays <= 3) {
                    self.moveNum = 0;
                } else {
                    self.moveNum = self.numDays - 2;
                }
            } else {
                self.numDays = 5;
                self.moveNum = 3;
            }
            console.log(self.dayNum);
        },
        /**
         * 滑动日期选择点击
         * dateNum 周几
         * year 年
         * month 月
         * date 日
         * obj 本对象
         **/
        dateClick: function() {
            var self = this;
            $('body').off('click','.date-list').on("click", ".date-list", function(e) {
                var year = $(this).attr('data-year');
                var month = $(this).attr('data-month');
                var date = $(this).attr('data-day');
                var select_time = year + '/' + self.prefixInteger(month, 2) + '/' + self.prefixInteger(date, 2);
                //判断选择的时间不能超过申请单时间
                if ($api.getStorage('travel_time').valueOf() > select_time.split('/').join('-').valueOf()) {
                    $alert('出行日期需大于等于出差申请单中的申请日期');

                    return false;
                }
                self.getNumDay(select_time);
                $(this).parent().find('.swiper-slide').removeClass('tomorrow');
                $(this).addClass('tomorrow');

                //发送监听
                //$api.setStorage('travel_time', select_time.split('/').join('-'));
                api.sendEvent({
                    name: 'timeChange',
                    extra: {
                        start_date: select_time.split('/').join('-')
                    }
                });
                self.params.start_date = select_time.split('/').join('-');
                self.getTrainList(self.params);
            });

        },
        //计算日期 平移效果
        calculate: function(Ymd) {
            var self = this;
            var width_num = $('.swiper-slide').eq(0).width();
            var distance = 0;
            distance = -width_num * self.moveNum;
            $('#calendar').css({
                'transform': 'translate3d(' + distance + 'px, 0px, 0px)',
                'transition-duration': '800ms'
            });
            self.calculateTime(Ymd);
        },
        //num传入的数字，n需要的字符长度  比如：2018-9-9  转换成 2018-09-09
        prefixInteger: function(num, n) {
            return (Array(n).join(0) + num).slice(-n);
        },
        /**
         *推算当天之后指定天数日历
         * @param assignDate 指定日期
         */
        calculateTime: function(assignDate) {
            var self = this;
            if (assignDate == undefined) {
                var now = new Date();
                var sign = false;
                assignDate = now.getFullYear() + '-' + now.getMonth() + '-' + now.getDay();
            } else {
                var now = new Date(Date.parse(assignDate));
                var sign = true;
            }
            var numDay = 15;
            var strtime;
            var htmlTime = " ";
            if (!sign) {
                for (var i = 0; i < numDay; i++) {
                    strtime = addDate(now, i);
                    var strMonth = getMonth(strtime).toString().length > 1 ? getMonth(strtime) : '0' + getMonth(strtime);
                    var strday = getDate(strtime).toString().length > 1 ? getDate(strtime) : '0' + getDate(strtime);
                    if (i == 1) {
                        htmlTime += '<div class="swiper-slide tomorrow date-list" data-i="' + i + '" data-year="' + getYear(strtime) + '" data-month="' + getMonth(strtime) + '" data-day="' + getDate(strtime) + '"><e>';
                        htmlTime += getDay(strtime);
                        htmlTime += '</e><c>';
                        htmlTime += strMonth + '-' + strday;
                        htmlTime += '</c></div>';
                    } else {
                        htmlTime += '<div class="swiper-slide date-list" data-i="' + i + '" data-year="' + getYear(strtime) + '" data-month="' + getMonth(strtime) + '" data-day="' + getDate(strtime) + '"><e>';
                        htmlTime += getDay(strtime);
                        htmlTime += '</e><c>';
                        htmlTime += strMonth + '-' + strday;
                        htmlTime += '</c></div>';
                    }
                }
            } else {
                for (var i = 0; i < numDay; i++) {
                    strtime = addDate(now, i);
                    var strMonth = getMonth(strtime).toString().length > 1 ? getMonth(strtime) : '0' + getMonth(strtime);
                    var strday = getDate(strtime).toString().length > 1 ? getDate(strtime) : '0' + getDate(strtime);
                    if (i == self.numDays) {
                        htmlTime += '<div class="swiper-slide tomorrow date-list" data-i="' + i + '" data-year="' + getYear(strtime) + '" data-month="' + getMonth(strtime) + '" data-day="' + getDate(strtime) + '"><e>';
                        htmlTime += getDay(strtime);
                        htmlTime += '</e><c>';
                        htmlTime += strMonth + '-' + strday;
                        htmlTime += '</c></div>';
                    } else {
                        htmlTime += '<div class="swiper-slide date-list" data-i="' + i + '" data-year="' + getYear(strtime) + '" data-month="' + getMonth(strtime) + '" data-day="' + getDate(strtime) + '"><e>';
                        htmlTime += getDay(strtime);
                        htmlTime += '</e><c>';
                        htmlTime += strMonth + '-' + strday;
                        htmlTime += '</c></div>';
                    }
                }
            }
            $('#calendar .date-list').remove();
            $('#calendar').prepend(htmlTime);
            /*日期轮播*/
            var swiper = new Swiper('.swiper-container', {
                slidesPerView: 5,
                spaceBetween: 0,
                freeMode: true,
                pagination: {
                    el: '.swiper-pagination'
                }
            });
        }
        //滑动日期绑定事件
        ,bindEv: function (){
            var self = this;
            var startDate = null;
            api.addEventListener({
                name: 'timeChange'
            }, function(ret, err) {
//            var el = $('#footer>div');
                startDate = ret.value.start_date;
                self.params.start_date = startDate.split('/').join('-');
                self.getNumDay(startDate);
                var confirmTime = getBeforeDate(self.numDays, startDate);
                self.calculate(confirmTime);
                // self.getTrainList(self.params); //step02:获取火车票列表
            });
        },
        //滑动日期绑定事件
          bindDate: function (){
            var self = this;
            var startDate = null;
            api.addEventListener({
                name: 'dateChange'
            }, function(ret, err) {
//            var el = $('#footer>div');
                startDate = ret.value.start_date;
                self.params.start_date = startDate.split('/').join('-');
                self.getNumDay(startDate);
                var confirmTime = getBeforeDate(self.numDays, startDate);
                self.calculate(confirmTime);
                // self.getTrainList(self.params); //step02:获取火车票列表
            });
        },
        //日历点击选择
        timeClick:function(){
          var self = this;
          /*打开日期选择*/
          var IsRun = false;
          $('#date-time').hotelDate({date:2,start_date:$api.getStorage('s_time')},function(ret){
            //判断选择的时间不能超过申请单时间
            if ($api.getStorage('travel_time').valueOf() > ret.enterTime.split('/').join('-').valueOf()) {
                $alert('出行日期需大于等于出差申请单中的申请日期');
                return false;
            }
              //选中时间
              var checkTime = ret.enterTime;
              api.sendEvent({
                  name: 'dateChange',
                  extra: {
                      start_date: checkTime.split('/').join('-')
                  }
              });
              self.params.start_date = checkTime.split('/').join('-');
              self.getNumDay(checkTime);
              var confirmTime = getBeforeDate(self.numDays, checkTime);
              self.getTrainList(self.params);
              if(IsRun) self.calculate(confirmTime);
              IsRun = true;
              $api.setStorage('is', false);
          });
        },
        //函数:扩展
        extend: function(a, b) {
            for (var key in b) {
                if (b.hasOwnProperty(key)) {
                    a[key] = b[key];
                }
            }
            return a;
        }

    };
    window.trainResult = trainResult;
})(window);
